﻿using System;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using WindowsPhoneMD5ClassLibrary;

namespace CarsRegistrationMobile.Managers
{
    public class StorageManager
    {
        #region Settings

        public void SaveSettings(params KeyValuePair<string, object>[] settings)
        {
            foreach (var setting in settings)
            {
                if (this.IsSettingExists(setting.Key))
                {
                    this.DeleteSetting(setting.Key);
                }

                IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
                appSettings.Add(setting.Key, setting.Value);
                appSettings.Save();
            }
        }
        public bool IsSettingExists(string setting_name)
        {
            return IsolatedStorageSettings.ApplicationSettings.Contains(setting_name);
        }
        public T GetSeting<T>(string setting_name)
        {
            try
            {
                return (T)IsolatedStorageSettings.ApplicationSettings[setting_name];
            }
            catch
            {
                return default(T);
            }
        }
        public void DeleteSetting(params string[] settings_names)
        {
            foreach (var settingName in settings_names)
            {
                IsolatedStorageSettings.ApplicationSettings.Remove(settingName);
            }
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        #endregion Settings

        #region Json

        public T GetJsonResult<T>(string json) where T : class
        {
            byte[] jsonData = Encoding.UTF8.GetBytes(json);
            T jsonResult = default(T);
            try
            {
                using (var ms = new MemoryStream(jsonData))
                {
                    var serializer = new DataContractJsonSerializer(typeof(T));
                    jsonResult = (T)serializer.ReadObject(ms);
                }
            }
            catch (Exception error)
            {
                // just return default value after getting exception
            }

            return jsonResult;
        }

        #endregion Json

        public string MD5Encode(string input)
        {
            var md5Manager = new MD5Manager();
            string result = md5Manager.GetMD5(input);
            return result;
        }
    }
}
